package multiprocessor;

import java.util.concurrent.Semaphore;
import java.util.function.IntConsumer;

//todo use other method
public class PrintZeroEvenOdd1116 {
    private int n;


    public PrintZeroEvenOdd1116(int n) {
        this.n = n;
    }

    Semaphore semaphore_odd = new Semaphore(0);
    Semaphore semaphore_event = new Semaphore(0);
    Semaphore semaphore = new Semaphore(1);

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i < n + 1; i++) {
            semaphore.acquire();

            printNumber.accept(0);

            if (i % 2 == 1) {
                semaphore_odd.release();
            } else {
                semaphore_event.release();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i < n + 1; i++) {
            if (i % 2 == 0) {
                semaphore_event.acquire();
                printNumber.accept(i);
                semaphore.release();
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i < n + 1; i++) {
            if (i % 2 == 1) {
                semaphore_odd.acquire();
                printNumber.accept(i);
                semaphore.release();
            }
        }
    }
}
